<template>
  <div :style="styleObj">
    <v-chart :options="options" autoresize/>
  </div>
</template>
<!--柱线图-->
<script>
export default {
  name: "WidgetBarlinechart",
  components: {},
  props: {
    value: Object,
    ispreview: Boolean
  },
  data() {
    return {
      options: {
        color: [],
        grid: {},
        title: {
          text: "test",
          textStyle: {
            color: "#fff"
          }
        },
        //提示框配置
        tooltip: {
          show: true,
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color:'rgba(9, 24, 48, 0.5)'
            }
          },
          backgroundColor: 'rgba(9, 24, 48, 0.8)', //提示框的背景颜色
          textStyle: {
            color: '#CFE3FC', //提示框的字体颜色
          },
          borderWidth: 0.1, //提示框的边框粗细
          borderColor: 'rgba(9, 24, 48, 1)', //提示框的边框颜色
          formatter: function (params) {
              let str = '<div style="text-align:left;">';
              for (let i = 0; i < params.length; i++) {
                  const name = params[i].seriesName
                  if (name.indexOf('series') == -1) {
                      if (i === 0) {
                          str += `${params[i].name}<br/>`;
                      }
                      if (name.indexOf("(") > 0) {
                          if (name.indexOf("(") > 0 && name.indexOf(")")) {
                              str += `${name.slice(0, name.indexOf('('))}：<span>${
                                  params[i].data
                              }</span>${name.slice(name.indexOf('(') + 1, name.indexOf(')'))}<br/>`;
                          }
                      } else {
                          str += `${name}：${params[i].data}<br/>`;
                      }
                  }
              }
              return str + "</div>";
          },
        },
        legend: {
          textStyle: {
            color: "#fff"
          },
          data: ["货运量", "货运总量"]
        },
        xAxis: [
          {
            type: "category",
            data: [],
            axisLabel: {
              show: false,
              textStyle: {
                color: "#fff"
              }
            }
          }
        ],
        yAxis: [
          {//左刻度线
            type: "value",
            name: "",
            min: 0,
            max: 250,
            interval: 50,
            axisLabel: {
              show: true,
              textStyle: {
                color: "#fff"
              }
            }
          },
          {
            //右刻度线
            type: "value",
            name: "",
            min: 0,
            max: 25,
            interval: 5,
            formatter: '{value} %',
            axisLabel: {
              show: true,
              textStyle: {
                color: "#fff"
              }
            }
          }
        ],
        series: []
      },
      optionsStyle: {}, // 样式
      optionsData: {}, // 数据
      optionsCollapse: {}, // 图标属性
      optionsSetup: {}
    };
  },
  computed: {
    styleObj() {
      return {
        position: this.ispreview ? "absolute" : "static",
        width: this.optionsStyle.width + "px",
        height: this.optionsStyle.height + "px",
        left: this.optionsStyle.left + "px",
        top: this.optionsStyle.top + "px",
        background: this.optionsSetup.background
      };
    }
  },
  watch: {
    value: {
      handler(val) {
        //console.log("valvalvalval",JSON.stringify(val.data))
        this.optionsStyle = val.position;
        this.optionsData = val.data;
        this.optionsCollapse = val.collapse;
        this.optionsSetup = val.setup;
        this.editorOptions();
      },
      deep: true
    }
  },
  created() {
    this.optionsStyle = this.value.position;
    this.optionsData = this.value.data;
    this.optionsCollapse = this.value.collapse;
    this.optionsSetup = this.value.setup;
    this.editorOptions();
  },
  methods: {
    // 修改图标options属性
     async editorOptions() {
       this.setOptionsTitle();
       await this.setOptionsData();
       this.setOptionsX();
       this.setOptionsY();
       this.setOptionsTooltip();
       this.setOptionsMargin();
       this.setOptionsLegend();
       this.setOptionsColor();
      console.log('this.options',JSON.stringify(this.options))
    },
    // 标题修改
    setOptionsTitle() {
      const optionsCollapse = this.optionsSetup;
      const title = {};
      title.text = optionsCollapse.titleText;
      title.show = optionsCollapse.isNoTitle;
      title.left = optionsCollapse.textAlign;
      title.textStyle = {
        color: optionsCollapse.textColor,
        fontSize: optionsCollapse.textFontSize,
        fontWeight: optionsCollapse.textFontWeight
      };
      title.subtext = optionsCollapse.subText;
      title.subtextStyle = {
        color: optionsCollapse.subTextColor,
        fontWeight: optionsCollapse.subTextFontWeight,
        fontSize: optionsCollapse.subTextFontSize
      };

      this.options.title = title;
    },
    // X轴设置
    setOptionsX() {
      const optionsCollapse = this.optionsSetup;
      const xAxis = {
        type: "category",
        show: optionsCollapse.hideX, // 坐标轴是否显示
        name: optionsCollapse.xName, // 坐标轴名称
        nameTextStyle: {
          color: optionsCollapse.nameColorX,
          fontSize: optionsCollapse.nameFontSizeX
        },
        nameRotate: optionsCollapse.textAngle, // 文字角度
        inverse: optionsCollapse.reversalX, // 轴反转
        axisLabel: {
          show: true,
          interval: optionsCollapse.textInterval, // 文字间隔
          rotate: optionsCollapse.textAngle, // 文字角度
          textStyle: {
            color: optionsCollapse.Xcolor, // x轴 坐标文字颜色
            fontSize: optionsCollapse.fontSizeX
          }
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: optionsCollapse.lineColorX
          }
        },
        splitLine: {
          show: optionsCollapse.isShowSplitLineX,
          lineStyle: {
            color: optionsCollapse.splitLineColorX
          }
        }
      };
      this.options.xAxis = xAxis;
    },
    // Y轴设置
    setOptionsY() {
      const optionsCollapse = this.optionsSetup;
      const yAxis = [
        {
          type: "value",
          splitNumber: optionsCollapse.splitNumberLeft,// 均分
          show: optionsCollapse.isShowYLeft, // 坐标轴是否显示
          name: optionsCollapse.textNameYLeft, // 坐标轴名称
          nameTextStyle: { // 别名
            color: optionsCollapse.nameColorYLeft,
            fontSize: optionsCollapse.namefontSizeYLeft
          },
          inverse: optionsCollapse.reversalY, // 轴反转
          axisLabel: {
            show: true,
            textStyle: {
              color: optionsCollapse.colorY, // y轴 坐标文字颜色
              fontSize: optionsCollapse.fontSizeY
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: optionsCollapse.lineColorY
            }
          },
          splitLine: {
            show: optionsCollapse.isShowSplitLineY,
            lineStyle: {
              color: optionsCollapse.splitLineColorY
            }
          }
        },
        {
          type: "value",
          splitNumber: optionsCollapse.splitNumberRight,// 均分
          show: optionsCollapse.isShowYRight, // 坐标轴是否显示
          name: optionsCollapse.textNameYRight, // 坐标轴名称
          nameTextStyle: { // 别名
            color: optionsCollapse.nameColorYRight,
            fontSize: optionsCollapse.namefontSizeYRight
          },
          inverse: optionsCollapse.reversalY, // 轴反转
          axisLabel: {
            show: true,
            textStyle: {
              color: optionsCollapse.colorY, // y轴 坐标文字颜色
              fontSize: optionsCollapse.fontSizeY
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: optionsCollapse.lineColorY
            }
          },
          splitLine: {
            show: false,
          }
        }
      ];
      this.options.yAxis = yAxis;
    },
    // 折线设置 数值设置
    setOptionsTop(item) {
        const optionsCollapse = this.optionsSetup;
        const series = {
            name: item.name,
            type: "line",
            yAxisIndex: 1,
            data: item.data,
            showSymbol: optionsCollapse.markPoint,
            symbolSize: optionsCollapse.pointSize,
            smooth: optionsCollapse.smoothCurve,
            lineStyle: {
                width: optionsCollapse.lineWidth
            },
            itemStyle: {
                borderRadius: optionsCollapse.radius
            },
            areaStyle: {
                opacity: optionsCollapse.area?optionsCollapse.areaThickness / 100:0
            },
            label: {
                show: optionsCollapse.isShowLine,
                position: "top",
                distance: optionsCollapse.distanceLine,
                fontSize: optionsCollapse.fontSizeLine,
                color: optionsCollapse.subTextColorLine,
                fontWeight: optionsCollapse.fontWeightLine
            }
        }
        return series

    },
    // 柱体设置 数值设置
      setOptionsBar(item) {
          const optionsCollapse = this.optionsSetup;
          const series = {
              name: item.name,
              type: "bar",
              data: item.data,
              itemStyle: {
                  barBorderRadius: null
              },
              label: {
                  show: optionsCollapse.isShowBar,
                  position: "top",
                  distance: optionsCollapse.distanceBar,
                  fontSize: optionsCollapse.fontSizeBar,
                  color: optionsCollapse.subTextColorBar,
                  fontWeight: optionsCollapse.fontWeightBar
              },
              barWidth: optionsCollapse.maxWidth,
              barMinHeight: optionsCollapse.minHeight,
              itemStyle: {barBorderRadius: optionsCollapse.radius}
          }
          return series
      },
    // tooltip 设置
    setOptionsTooltip() {
      const optionsCollapse = this.optionsSetup;
      this.options.tooltip.textStyle = {
          color: optionsCollapse.lineColor,
          fontSize: optionsCollapse.tipFontSize
        }
    },
    // 边距设置
    setOptionsMargin() {
      const optionsCollapse = this.optionsSetup;
      const grid = {
        left: optionsCollapse.marginLeft,
        right: optionsCollapse.marginRight,
        bottom: optionsCollapse.marginBottom,
        top: optionsCollapse.marginTop,
        containLabel: true
      };
      this.options.grid = grid;
    },
    // 图例操作 legend
    setOptionsLegend() {
      const optionsCollapse = this.optionsSetup;
      this.options.legend={
        show : optionsCollapse.isShowLegend,
        left : optionsCollapse.lateralPosition == "left" ? 0 : "auto",
        right : optionsCollapse.lateralPosition == "right" ? 0 : "auto",
        top : optionsCollapse.longitudinalPosition == "top" ? 0 : "auto",
        bottom :optionsCollapse.longitudinalPosition == "bottom" ? 0 : "auto",
        orient : optionsCollapse.layoutFront,
        textStyle : {
          color: optionsCollapse.lengedColor,
          fontSize: optionsCollapse.fontSize
        },
        itemWidth : optionsCollapse.lengedWidth
      }
    },
    // 图例颜色修改
    setOptionsColor() {
      const optionsCollapse = this.optionsSetup;
      const customColor = optionsCollapse.customColor;
      if (!customColor) return;
      const arrColor = [];
      for (let i = 0; i < customColor.length; i++) {
        arrColor.push(customColor[i].color);
      }
      this.options.color = arrColor;
      this.options = Object.assign({}, this.options);
    },
    // 数据处理
    setOptionsData() {
      const optionsData = this.optionsData; // 数据类型 静态 or 动态
      //console.log(optionsData);
      optionsData.dataType == "staticData"
        ? this.staticDataFn(optionsData.staticData)
        : this.dynamicDataFn(optionsData.dynamicData, optionsData.refreshTime);
        console.log("optionsData.dynamicData",optionsData.dynamicData)
    },
    /**
     * 设置静态数据
     */
    staticDataFn(val) {
      const staticData = typeof val == "string" ? JSON.parse(val) : val;
      // x轴
      this.options.series=[]
      this.options.xAxis.data = staticData.xAxis;
      this.initSeries(staticData.series)
    },
    /**
     * 初始化series
     */
    initSeries(data) {
      //如果已经有数据，不再重复初始化
      //if(this.options.series.length>0){
       // return false
      //}
      // series
      const series = this.options.series;
      //console.log('this.value.setup',this.value.setup.dynamicPropertyDict)
      for (const i in data) {
         const item = data[i]
         //柱
        if (item.type=='bar'){
          series.push(this.setOptionsBar(item))
          //线
        }else if(item.type=='line'){
            series.push(this.setOptionsTop(item))
        }else{
          console.log("不支持的series类型",item.type)
          return false
        }
      }
    },
    /**
     * 设置动态数据
     */
    dynamicDataFn(val, refreshTime) {
      if (!val) return;
      if (this.ispreview) {
        this.getEchartData(val);
        this.flagInter = setInterval(() => {
          this.getEchartData(val);
        }, refreshTime);
      } else {
        this.getEchartData(val);
      }
    },
    getEchartData(val) {
      const dict=this.value.setup.dynamicPropertyDict
      const data = this.queryEchartsData(val,dict);
      data.then(res => {
        this.renderingFn(res);
      });
    },
    renderingFn(val) {
      this.options.xAxis.data = val.xAxis;
      // series
      this.options.series=[]
      this.initSeries(val.series)
    }
  }
};
</script>

<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
